package com.ruoyi.project.system.attachment.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.attachment.domain.Attachment;
import com.ruoyi.project.system.attachment.service.IAttachmentService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;

/**
 * 附件Controller
 * 
 * @author ruoyi
 * @date 2019-10-31
 */
@Controller
@RequestMapping("/system/attachment")
public class AttachmentController extends BaseController
{
    private String prefix = "system/attachment";

    @Autowired
    private IAttachmentService attachmentService;

    @RequiresPermissions("system:attachment:view")
    @GetMapping()
    public String attachment()
    {
        return prefix + "/attachment";
    }

    /**
     * 查询附件列表
     */
    @RequiresPermissions("system:attachment:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Attachment attachment)
    {
        startPage();
        List<Attachment> list = attachmentService.selectAttachmentList(attachment);
        return getDataTable(list);
    }

    /**
     * 导出附件列表
     */
    @RequiresPermissions("system:attachment:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Attachment attachment)
    {
        List<Attachment> list = attachmentService.selectAttachmentList(attachment);
        ExcelUtil<Attachment> util = new ExcelUtil<Attachment>(Attachment.class);
        return util.exportExcel(list, "attachment");
    }

    /**
     * 新增附件
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存附件
     */
    @RequiresPermissions("system:attachment:add")
    @Log(title = "附件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Attachment attachment)
    {
        return toAjax(attachmentService.insertAttachment(attachment));
    }

    /**
     * 修改附件
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        Attachment attachment = attachmentService.selectAttachmentById(id);
        mmap.put("attachment", attachment);
        return prefix + "/edit";
    }

    /**
     * 修改保存附件
     */
    @RequiresPermissions("system:attachment:edit")
    @Log(title = "附件", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Attachment attachment)
    {
        return toAjax(attachmentService.updateAttachment(attachment));
    }

    /**
     * 删除附件
     */
    @RequiresPermissions("system:attachment:remove")
    @Log(title = "附件", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(attachmentService.deleteAttachmentByIds(ids));
    }


    /**
     * 使用MultipartFile上传文件
     * <请替换成功能描述> <br>
     * <请替换成详细描述>
     * @param file
     * @return
     * @author caizh
     * @since [1.0.0]
     * @version [1.0.0,2017年2月5日]
     */
    @RequestMapping("/upload_03")
    public String fileUpload_3(@RequestParam(value="file_03",required=false)MultipartFile file,
                               HttpServletRequest request){
        long startTime = System.currentTimeMillis();
        //String path = request.getSession().getServletContext().getRealPath("upload");
        String path = "E:/springUpload/";
        System.out.println(path);
        String fileName = file.getOriginalFilename();
        File targetFile = new File(path,fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        //保存
        try {
            file.transferTo(targetFile);
        }catch(Exception e){
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("方法三的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return prefix + "/success";
    }

    /**
     * 采用spring提供的上传文件的方法
     * <请替换成功能描述> <br>
     * <请替换成详细描述>
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     * @author caizh
     * @since [1.0.0]
     * @version [1.0.0,2017年2月5日]
     */
    @RequestMapping("/upload_spring")
    public String springUpload(HttpServletRequest request)throws IllegalStateException, IOException {
        long startTime = System.currentTimeMillis();
        String path = "E:/springUpload/";
        String newpath = null;
        String filename = null;
        //将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //获取multiRequest中所有的文件名
            Iterator iter = multiRequest.getFileNames();

            while(iter.hasNext()){
                //一次遍历所有的文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                filename = file.getOriginalFilename();
                if(file!=null){
                    newpath = path + filename;
                    //上传
                    file.transferTo(new File(newpath));
                }
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("方法四的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return prefix + "/add";
//        return null;
    }


}
